import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:yysk_app/utils/colors.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';

class MyWebViewForAppPage extends StatefulWidget {
  const MyWebViewForAppPage({super.key});
  static const path = '/webViewApp';

  @override
  State<MyWebViewForAppPage> createState() => _MyWebViewForAppPageState();
}

class _MyWebViewForAppPageState extends State<MyWebViewForAppPage> {
  late String url;
  InAppWebViewController? webViewController;
  bool _permissionsGranted = false;
  late String _titleName = '元宇时空';
  @override
  void initState() {
    super.initState();
  
    _initUrl();
  }

  void _initUrl() {
    try {
      final params = Get.parameters ?? {};
      final args = Get.arguments ?? {};
      var rawUrl = params['url'] ?? args['url'];
      // var needPermissions = args['needPermissions'] ?? false;
      // if (needPermissions) {
      //   _checkPermissions();
      // }
        setState(() {
      _titleName = args['title'] ?? '元宇时空';
    });
      if (rawUrl == null) {
        Get.back();
        Get.snackbar('错误', 'URL 无效');
        return;
      }

      url = Uri.decodeComponent(rawUrl);
    } catch (e) {
      debugPrint('解析 URL 失败: $e');
      Get.back();
      Get.snackbar('错误', 'URL 格式不正确');
    }
  }

  Future<void> _checkPermissions() async {
    // 请求摄像头和麦克风权限
    final status = await [Permission.camera, Permission.microphone].request();

    if (status[Permission.camera]!.isGranted &&
        status[Permission.microphone]!.isGranted) {
      setState(() => _permissionsGranted = true);
    } else {
      Get.snackbar('权限被拒绝', '请前往设置开启权限');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title:  Text(_titleName),backgroundColor:AppColors.fontColor,),
      body:
          _permissionsGranted
              ? _buildWebView()
              : const Center(child: CircularProgressIndicator()),
    );
  }

  Widget _buildWebView() {
    return InAppWebView(
      initialUrlRequest: URLRequest(url: WebUri(url)),
      initialOptions: InAppWebViewGroupOptions(
        crossPlatform: InAppWebViewOptions(
          mediaPlaybackRequiresUserGesture: false,
          javaScriptEnabled: true,
          javaScriptCanOpenWindowsAutomatically: true,
        ),
        android: AndroidInAppWebViewOptions(
          useHybridComposition: true,
          allowFileAccess: true,
        ),
        ios: IOSInAppWebViewOptions(allowsInlineMediaPlayback: true),
      ),
      onWebViewCreated: (controller) {
        webViewController = controller;
      },
      onPermissionRequest: (controller, request) async {
        // 处理网页内的权限请求
        return PermissionResponse(
          resources: request.resources,
          action: PermissionResponseAction.GRANT,
        );
      },
    );
  }
}
